﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
using BISPOS.Repository;
namespace BISPOS
{
    public partial class AddBillUserControl : DevExpress.XtraEditors.XtraUserControl
    {
        List<BillItemGridItem> gridItems = new List<BillItemGridItem>();
        IEnumerable<Product> allProducts;
        ProductRepository productRepository = new ProductRepository();
        StockRepository stockRepository = new StockRepository();
        Product currentProduct;
        Supplier supplier=null;
        BISPOSDataClassesDataContext db = new BISPOSDataClassesDataContext();

        public AddBillUserControl()
        {
            InitializeComponent();
            allProducts = productRepository.AllProducts();
            billItemslinqServerModeSource.QueryableSource = gridItems.AsQueryable();
            this.dateDateEdit.DateTime = DateTime.Now;
        }
        public void AddSupplier(Supplier _supplier)
        {
            supplier = _supplier;
            supplierTextEdit.Text = supplier.Name;
        }
        public void UpdatePrice()
        {
            try
            {
                allCosttextEdit.Text = gridItems.Sum(x => x.Cost).ToString("n2");
            }
            catch { allCosttextEdit.Text = "0.00"; }
        }
        public void ClearProduct()
        {
            currentProduct = null;
            productNameTextEdit.ResetText();
            productUnitTextEdit.ResetText();
            quantityTextEdit.ResetText();
            costTextEdit.ResetText();
            addProductButton.Enabled = false;
            barcodeTextEdit.ResetText();
            barcodeTextEdit.Focus();

        }
        private void barcodeTextEdit_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Product product = allProducts.FirstOrDefault(x => x.Barcode == barcodeTextEdit.Text);
                currentProduct = product;
                if (product != null)
                {
                    currentProduct = product;
                    productNameTextEdit.Text = product.BarcodeAndName;
                    productUnitTextEdit.Text = product.Unit;
                    quantityTextEdit.Focus();
                }
                else
                {
                    MessageBox.Show("ไม่พบสินค้า");
                }

            }
        }

        private void costTextEdit_EditValueChanged(object sender, EventArgs e)
        {
            addProductButton.Enabled = true;
        }

        private void addProductButton_Click(object sender, EventArgs e)
        {
            gridItems.Add(new BillItemGridItem
            {
                Cost = Convert.ToDecimal(costTextEdit.Text),
                ProductId = currentProduct.Id,
                ProductName = currentProduct.Name,
                Quantity = Convert.ToDouble(quantityTextEdit.Text),
                UnitCost = (Convert.ToDouble(costTextEdit.Text)) / (Convert.ToDouble(quantityTextEdit.Text))

            });
            billItemslinqServerModeSource.QueryableSource = gridItems.AsQueryable();
            ClearProduct();
            UpdatePrice();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            AddBill_SelectSupplierForm form = new AddBill_SelectSupplierForm(this);
            form.Show();
        }

        private void billItemsgridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                try
                {
                    gridItems.Remove((BillItemGridItem)billItemsgridView.GetRow(billItemsgridView.GetSelectedRows()[0]));
                    billItemslinqServerModeSource.Reload();
                    UpdatePrice();
                    ClearProduct();
                }
                catch { }
            }
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            Bill bill = new Bill
            {
                Date = dateDateEdit.DateTime,
                IsCredit = isCreditCheckEdit.Checked,
                Note = noteMemoEdit.Text,
                SupplierId = supplier.Id
            };


            foreach (var gridItem in gridItems)
            {
                productRepository = new ProductRepository();
                Product product = productRepository.Get(gridItem.ProductId);
                if (product.Stocks.Count > 0)
                {
                    if (product.FirstAvailableStock != null)
                    {
                        if (product.FirstAvailableStock.CurrentQuantity >= 0)
                        {
                            Stock newStock = new Stock
                            {
                                BuyingCost = gridItem.Cost,
                                CurrentQuantity = gridItem.Quantity,
                                Date = bill.Date,
                                OriginalQuantity = gridItem.Quantity,
                                ProductId = product.Id
                            };
                            bill.BillItems.Add(new BillItem
                            {
                                Stock = newStock
                            });

                            db.Stocks.InsertOnSubmit(newStock);
                            db.Bills.InsertOnSubmit(bill);
                            db.SubmitChanges();
                        }
                        else // Stock ติดลบ
                        {


                            if ((product.FirstAvailableStock.CurrentQuantity + gridItem.Quantity) >= 0)
                            {
                                int id = product.FirstAvailableStock.Id;
                                stockRepository.EditStock(id, gridItem.Quantity,
                                    product.FirstAvailableStock.CurrentQuantity + gridItem.Quantity,
                                    gridItem.Cost,
                                    bill.Date);
                                db.SubmitChanges();

                                bill.BillItems.Add(new BillItem
                                {
                                    StockId = id
                                });

                                db.Bills.InsertOnSubmit(bill);
                                db.SubmitChanges();
                            }
                            else
                            {
                                double currentQuantity = product.FirstAvailableStock.CurrentQuantity;
                                stockRepository.EditStock(product.FirstAvailableStock.Id, gridItem.Quantity, 0, gridItem.Cost, bill.Date);

                                Stock newStock = new Stock
                                {
                                    BuyingCost = 0,
                                    CurrentQuantity = currentQuantity + gridItem.Quantity,
                                    Date = DateTime.Now,
                                    OriginalQuantity = 0,
                                    ProductId = product.Id
                                };
                                db.SubmitChanges();
                                bill.BillItems.Add(new BillItem
                                {
                                    Stock = newStock
                                });

                                db.Stocks.InsertOnSubmit(newStock);
                                db.Bills.InsertOnSubmit(bill);
                                db.SubmitChanges();

                            }
                        }
                    }
                    else
                    {
                        Stock newStock = new Stock
                        {
                            BuyingCost = gridItem.Cost,
                            CurrentQuantity = gridItem.Quantity,
                            Date = bill.Date,
                            OriginalQuantity = gridItem.Quantity,
                            ProductId = product.Id
                        };

                        db.Stocks.InsertOnSubmit(newStock);
                        db.SubmitChanges();

                        bill.BillItems.Add(new BillItem
                        {
                            StockId = newStock.Id
                        });

                        db.Bills.InsertOnSubmit(bill);
                        db.SubmitChanges();
                    }
                    
                }
                else
                {
                    Stock newStock = new Stock
                    {
                        BuyingCost = gridItem.Cost,
                        CurrentQuantity = gridItem.Quantity,
                        Date = bill.Date,
                        OriginalQuantity = gridItem.Quantity,
                        ProductId = product.Id
                    };

                    db.Stocks.InsertOnSubmit(newStock);
                    db.SubmitChanges();

                    bill.BillItems.Add(new BillItem
                    {
                        StockId = newStock.Id
                    });

                    db.Bills.InsertOnSubmit(bill);
                    db.SubmitChanges();
                }
            }
            
            ClearForm();
        }
        public void ClearForm()
        {
            ClearProduct();
            billItemslinqServerModeSource.QueryableSource = null;
            supplier = null;
            supplierTextEdit.ResetText();
            dateDateEdit.DateTime = DateTime.Now;
            isCreditCheckEdit.Checked = false;
            noteMemoEdit.ResetText();
            gridItems.Clear();
            UpdatePrice();
        }

    }
}
